package com.artron.mediaartron.ui.fragment.login;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.Altar;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.LoginApi;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.activity.LoginActivity;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.artron.mediaartron.ui.widget.DrawableTextViewWrapper;
import com.artron.mediaartron.util.RegexUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-17.
 */

public class RegisterFragment extends BaseStaticFragment implements View.OnClickListener {

    @BindView(R.id.RegisterFragment_ll_container)
    protected LinearLayout mLlContainer;
    @BindView(R.id.RegisterFragment_et_number)
    protected EditText mEtNumber;
    @BindView(R.id.RegisterFragment_et_code)
    protected EditText mEtCode;
    @BindView(R.id.RegisterFragment_btn_captcha)
    protected Button mBtnCaptcha;
    @BindView(R.id.RegisterFragment_et_password)
    protected EditText mEtPassword;
    @BindView(R.id.RegisterFragment_cb_treaty)
    protected CheckBox mCbTreaty;
    @BindView(R.id.RegisterFragment_tv_treaty)
    protected TextView mTvTreaty;
    @BindView(R.id.RegisterFragment_ll_treaty)
    protected LinearLayout mLlTreaty;
    @BindView(R.id.RegisterFragment_tv_treaty_text)
    protected TextView mTvTreatyText;
    @BindView(R.id.RegisterFragment_btn_finish)
    protected Button mBtnFinish;
    private int mType;
    private int mCaptchaSecond = 0;
    private boolean isCanClickCaptcha = true;
    private Timer mTimer;

    public static RegisterFragment newInstance(int type) {
        RegisterFragment fragment = new RegisterFragment();
        fragment.init(type);
        return fragment;
    }

    private void init(int type) {
        this.mType = type;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_register;
    }

    @Override
    protected void initView() {
        if (mType == LoginActivity.TYPE_REGISTER || mType == LoginActivity.TYPE_BIND_PHONE) {
            mEtPassword.setHint("设置密码");
        } else {
            mEtPassword.setHint("新密码");
            mLlTreaty.setVisibility(View.GONE);
            getActivity().invalidateOptionsMenu();
        }

        DrawableTextViewWrapper wrapper = new DrawableTextViewWrapper(mEtPassword);
        wrapper.setDrawableRightClickListener(new DrawableTextViewWrapper.DrawableRightClickListener() {

            private boolean isVisible = false;

            @Override
            public void onDrawableRightClickListener(View view) {
                if (isVisible) {
                    mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mEtPassword.setCompoundDrawablesWithIntrinsicBounds(null, null
                            , UIUtils.getDrawable(R.drawable.ic_password_invisible), null);
                } else {
                    mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mEtPassword.setCompoundDrawablesWithIntrinsicBounds(null, null
                            , UIUtils.getDrawable(R.drawable.ic_password_visible), null);
                }
                isVisible = !isVisible;
            }
        });

        mTvTreatyText.setOnClickListener(this);
        mBtnFinish.setOnClickListener(this);
        ThrottleFirstClickHelper.throttleFirst(mBtnCaptcha, this);
        mLlContainer.setOnClickListener(this);
        mTvTreaty.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_register:
                getActivity().onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.RegisterFragment_tv_treaty_text:
                mCbTreaty.setChecked(!mCbTreaty.isChecked());
                break;

            case R.id.RegisterFragment_btn_finish:
                String mobile1 = mEtNumber.getText().toString();
                String captcha = mEtCode.getText().toString();
                String password = mEtPassword.getText().toString();

                if (!RegexUtils.isTelPhoneNum(mobile1)) {
                    ToastUtil.show("请输入正确手机号");
                    return;
                }

                if (!TextUtils.isEmpty(mobile1) &&
                        !TextUtils.isEmpty(captcha) &&
                        !TextUtils.isEmpty(password)) {
                    if (mType == LoginActivity.TYPE_REGISTER) {
                        register(mobile1, captcha, password);
                    } else if (mType == LoginActivity.TYPE_BIND_PHONE) {
                        bindPhone(mobile1, captcha, password);
                    } else {
                        resetPassword(mobile1, captcha, password);
                    }
                } else {
                    UIUtils.showSnackbar(getView(), "请输入完整信息");
                }
                break;

            case R.id.RegisterFragment_btn_captcha:
                UIUtils.hiddenKeyboard(getView());
                String mobile2 = mEtNumber.getText().toString();
                if (RegexUtils.isTelPhoneNum(mobile2)) {
                    getCaptcha(mobile2);
                } else {
                    ToastUtil.show("请输入正确手机号");
                }
                break;
            case R.id.RegisterFragment_ll_container:
                UIUtils.hiddenKeyboard(getView());
                break;
            case R.id.RegisterFragment_tv_treaty://注册协议
                GeneralActivity.start(mContext, GeneralActivity.HELP, "传给雅昌注册协议",
                        "http://pms.artup.com/pms/help/protocol.html");
                break;
        }
    }


    private void register(String mobile, String captcha, String password) {
        LoginApi loginApi = RetrofitHelper.getLoginApi();
        RetrofitHelper.subscript(loginApi.register(mobile, captcha, password),
                new Action1<Response>() {
                    @Override
                    public void call(Response response) {
                        if ("FAILED".equals(response.getStatus())) {
                            UIUtils.showSnackbar(getView(), response.getMessage());
                        } else {
                            UIUtils.showSnackbar(getView(), "注册成功");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    getActivity().onBackPressed();
                                }
                            }, 1000);
                        }
                    }
                });
    }

    private void bindPhone(String mobile, String captcha, String password) {
        Altar altar = AppProfile.getUserInfo();
        String utoken = altar.getUser().getUtoken();
        LoginApi loginApi = RetrofitHelper.getLoginApi();
        RetrofitHelper.subscript(loginApi.bindMobile(utoken, mobile, captcha, password), new Action1<Response>() {
            @Override
            public void call(Response response) {
                if ("FAILED".equals(response.getStatus())) {
                    UIUtils.showSnackbar(getView(), response.getMessage());
                } else {
                    UIUtils.showSnackbar(getView(), "绑定成功");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getActivity().onBackPressed();
                        }
                    }, 1000);
                }
            }
        });
    }

    private void getCaptcha(String mobile) {
        if (isCanClickCaptcha) {
            LoginApi loginApi = RetrofitHelper.getLoginApi();
            RetrofitHelper.subscript(loginApi.getCaptcha(mobile), new Action1<Response>() {
                @Override
                public void call(Response response) {
                    if ("OK".equals(response.getStatus())) {
                        UIUtils.showSnackbar(getView(), response.getMessage());
                        startCaptcha();
                    } else {
                        UIUtils.showSnackbar(getView(), "发送验证码失败，请检查网络");
                    }
                }
            });
        }
    }

    private void startCaptcha() {
        mCaptchaSecond = 60;
        isCanClickCaptcha = false;
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCaptchaSecond--;
                        if (mCaptchaSecond == 0) {
                            mBtnCaptcha.setText("重新发送");
                            isCanClickCaptcha = true;
                            mTimer.cancel();
                        } else {
                            mBtnCaptcha.setText(mCaptchaSecond + "s，重新发送");
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    private void resetPassword(String mobile, String captcha, String password) {
        LoginApi loginApi = RetrofitHelper.getLoginApi();
        RetrofitHelper.subscript(loginApi.resetPassword(mobile, captcha, password),
                new Action1<Response>() {
                    @Override
                    public void call(Response response) {
                        if ("FAILED".equals(response.getStatus())) {
                            UIUtils.showSnackbar(getView(), response.getMessage());
                        } else {
                            UIUtils.showSnackbar(getView(), "重置成功");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    getActivity().onBackPressed();
                                }
                            }, 1000);
                        }
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
        }
    }
}
